package com.example.demo.school.repositories;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Optional;


public abstract class BaseRepository<T> {

    @PersistenceContext
    protected EntityManager entityManager;

    private final Class<T> entityClass;

    @SuppressWarnings("unchecked")
    public BaseRepository() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }


    protected <S> Optional<S> first(List<S> results) {
        return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0));
    }

    public Optional<T> findOptional(Object primaryKey) {
        return Optional.ofNullable(entityManager.find(entityClass, primaryKey));

    }

    public void save(T entity) {
        entityManager.persist(entity);
    }


    public void delete(T entity) {
        entityManager.remove(entity);
    }

    public TypedQuery<T> createQuery(String qlString) {

        return entityManager.createQuery(qlString, entityClass);
    }

    public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass) {
        return entityManager.createQuery(qlString, resultClass);
    }
}
